package com.hhb.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhb.config.MinioConfig;
import com.hhb.constant.BaseController;
import com.hhb.constant.PageData;
import com.hhb.constant.Result;
import com.hhb.constant.UploadImgConstant;
import com.hhb.entity.Trainer;
import com.hhb.entity.pojo.TrainerDTO;
import com.hhb.service.ITrainerService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 培训师 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-09-26
 */
@RestController
@RequestMapping("/trainer")
@CrossOrigin
public class TrainerController extends BaseController {
    @Resource
    ITrainerService trainerService;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    MinioConfig minioConfig;
    @PostMapping("/getTrainerByPage/{pageNum}/{pageSize}")
    public Result getTrainerByPage(@PathVariable("pageNum")Integer pageNum,
                                   @PathVariable("pageSize")Integer pageSize,
                                   @RequestBody TrainerDTO trainerDTO){
        Page<Trainer> p = new Page<>(pageNum,pageSize);
        QueryWrapper<Trainer> wrapper = new QueryWrapper<>();
        if (trainerDTO!=null){
            if (trainerDTO.getName()!=null && (!trainerDTO.getName().trim().equals(""))){
                    wrapper.like("name",trainerDTO.getName());
            }
            if (trainerDTO.getLevel()!=null){
                wrapper.eq("level",trainerDTO.getLevel());
            }
            if (trainerDTO.getCreateTimeStart()!=null){
                wrapper.ge("create_time",trainerDTO.getCreateTimeStart());
            }
            if (trainerDTO.getCreateTimeEnd()!=null){
                wrapper.le("create_time",trainerDTO.getCreateTimeEnd());
            }
        }
        wrapper.orderByDesc("sort");
        Page<Trainer> page = trainerService.page(p,wrapper);
        PageData pageData = new PageData(page.getTotal(), page.getRecords());
        return this.toDataResult(pageData);
    }
    @RequiresPermissions(value = {"trainer:add","trainer:edit"})
    @PostMapping("/saveOrUpdataTrainer")
    public Result saveOrUpdataTrainer(@RequestBody Trainer trainer){
        boolean b = trainerService.saveOrUpdate(trainer);
        if (b && trainer.getAvatar()!=null && !trainer.getAvatar().equals("")){

            String bucketName = minioConfig.getBucketName();
            int start = trainer.getAvatar().indexOf(bucketName)+bucketName.length()+1;
            int end = trainer.getAvatar().indexOf("?");
            String imgName = trainer.getAvatar().substring(start,end);
            stringRedisTemplate.opsForSet().add(UploadImgConstant.saveImg,imgName);
        }
        return this.success2(b);
    }
    @GetMapping("/SelectTrainerById/{id}")
    public Result SelectTrainerById(@PathVariable("id")String id){
        Trainer byId = trainerService.getById(id);
        return this.toDataResult(byId);
    }
    @RequiresPermissions(value = {"trainer:delete"})
    @DeleteMapping("/deleteTrainerById/{id}")
    public Result deleteTrainerById(@PathVariable("id")String id){
        boolean b = trainerService.removeById(id);
        return this.success2(b);
    }
    @GetMapping("/DownloadTrainer")
    public Result DownloadTrainer(HttpServletResponse response) throws IOException {
        try {
            List<Trainer> data = trainerService.list();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("培训师列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Trainer.class).sheet("模板").doWrite(data);
        } catch (IOException e) {
            return this.toDataResult("导出失败");
        }
        return this.success();
    }
    @GetMapping("/getTrainerNameId")
    public Result getTrainerNameId(){
        return this.toDataResult(trainerService.getTrainerNameId());
    }

}
